package types

import (
	"fmt"
)

// ProtocolType 协议类型枚举
type ProtocolType string

const (
	Tcp        = "TCP"
	RtuOverTcp = "RTU_OVER_TCP"
	Rtu        = "RTU"
)

type RegisterType int32

const (
	Coil RegisterType = iota + 1
	DiscreteInput
	HoldingRegister
	InputRegister
)

// ModbusFunctionCode 定义 Modbus 功能码枚举
type ModbusFunctionCode int32

const (
	ReadCoilRegisters            ModbusFunctionCode = 1
	ReadDiscreteInputRegisters   ModbusFunctionCode = 2
	ReadHoldingRegisters         ModbusFunctionCode = 3
	ReadInputRegisters           ModbusFunctionCode = 4
	WriteSingleCoilRegister      ModbusFunctionCode = 5
	WriteSingleHoldingRegister   ModbusFunctionCode = 6
	WriteMultipleCoilRegisters   ModbusFunctionCode = 15
	WriteMultipleHolingRegisters ModbusFunctionCode = 16
)

// TcpConfig Tcp 配置结构体
type TcpConfig struct {
	ProtocolType ProtocolType
	Host         string
	Port         int32
}

// RtuConfig Rtu 配置结构体
type RtuConfig struct {
	Port     string
	Baudrate int32
	Parity   string
	Stopbits int32
	Bytesize int32
	Timeout  int32
}

// InnerDecode 定义解码类型
type InnerDecode int

const (
	UnsignedShort InnerDecode = iota
	SignedShort
	LongABCD
	LongCDAB
	LongBADC
	LongDCBA
	FloatABCD
	FloatCDAB
	FloatBADC
	FloatDCBA
)

// ByteOrder 定义字节序类型
type ByteOrder int

const (
	BigEndUnsignedShort ByteOrder = iota
	BigEndSignedShort
	BigEndSignedInt
	BigEndWordSwappedSignedInt
	LittleEndWordSwappedSignedInt
	LittleEndSignedInt
	BigEndFloat
	WordSwappedFloat
	LittleEndWordSwappedFloat
	LittleEndFloat
)

// byteorderMapping 字节序映射
var byteorderMapping = map[InnerDecode]ByteOrder{
	UnsignedShort: BigEndUnsignedShort,
	SignedShort:   BigEndSignedShort,
	LongABCD:      BigEndSignedInt,
	LongCDAB:      BigEndWordSwappedSignedInt,
	LongBADC:      LittleEndWordSwappedSignedInt,
	LongDCBA:      LittleEndSignedInt,
	FloatABCD:     BigEndFloat,
	FloatCDAB:     WordSwappedFloat,
	FloatBADC:     LittleEndWordSwappedFloat,
	FloatDCBA:     LittleEndFloat,
}

// parseDataType 将字符串类型的 dataType 解析为 InnerDecode 类型
func parseDataType(dataType string) (InnerDecode, error) {
	switch dataType {
	case "UnsignedShort":
		return UnsignedShort, nil
	case "SignedShort":
		return SignedShort, nil
	case "LongABCD":
		return LongABCD, nil
	case "LongCDAB":
		return LongCDAB, nil
	case "LongBADC":
		return LongBADC, nil
	case "LongDCBA":
		return LongDCBA, nil
	case "FloatABCD":
		return FloatABCD, nil
	case "FloatCDAB":
		return FloatCDAB, nil
	case "FloatBADC":
		return FloatBADC, nil
	case "FloatDCBA":
		return FloatDCBA, nil
	default:
		return 0, fmt.Errorf("不支持的数据类型: %s", dataType)
	}
}

// getByteOrder 根据数据类型获取字节序
func GetByteOrder(dataType string) (ByteOrder, error) {
	innerDecode, err := parseDataType(dataType)
	if err != nil {
		return 0, err
	}
	byteorder, ok := byteorderMapping[innerDecode]
	if !ok {
		return BigEndSignedInt, fmt.Errorf("未找到对应字节序，默认使用 BigEndSignedInt")
	}
	return byteorder, nil
}
